const Service = require('egg').Service;
const lodash = require('lodash');

class SysMenuService extends Service {
    /**
     * 新增
     * @param {提交的数据} data 
     * @return 1，0
     */
    async create(data) {
        const { ctx, app } = this;
        let rs = await ctx.model.SysMenu.create(data);
    }

    /**
     * 编辑
     * @param {提交的数据} data 
     * @return 1，0
     */
    async update(data, menu_id) {
        const { ctx, app } = this;
        let rs = await ctx.model.SysMenu.update(data, { where: { menu_id } });
    }

    /**
     * 查询列表
     * @param {提交的数据} data 
     * @return 1，0
     */
    async querylist(queryParams) {
        const { ctx, app } = this;
        queryParams = queryParams || {};
        return {
            datalist: await ctx.service.sysMenu.queryTreeList(queryParams)
        }
    }

    /**
     * 删除
     * @param {提交的数据} data 
     * @return 1，0
     */
    async delete(id) {
        const { ctx, app } = this;
        let rs = await ctx.model.SysMenu.destroy({ "where": { menu_id: id } });
    }

    /**
     * 删除
     * @param {提交的数据} data 
     * @return 1，0
     */
    async deleteLogic(id) {
        const { ctx, app } = this;
        let rs = await ctx.model.SysMenu.update({ deleted: "1" }, { "where": { menu_id: id } });
    }

    /**
     * 查询详情
     * @param {提交的数据} data 
     * @return 1，0
     */
    async queryById(id) {
        const { ctx, app } = this;
        let rs = await ctx.model.SysMenu.findOne({ where: { menu_id: id } });
        return rs;
    }

    /**
     * 查询列表
     * @param {提交的数据} data 
     * @return 1，0
     */
    async queryTreeList(queryParams) {
        const { ctx, app } = this;
        queryParams = queryParams || {};

        //方便更改,使用 sql 查询,以下步骤为生产sql的过程
        let whereSQL = "where";
        let whereParams = {};
        if (! await app.utils.validator.isEmpty(queryParams['search'])) {

            whereParams['menu_name'] = queryParams['search'];
            whereParams['perms'] = queryParams['search'];
            whereSQL = whereSQL + ` (t.menu_name Like CONCAT('%',:menu_name,'%') or t.perms Like CONCAT('%',:perms,'%'))`;
        }
        if (whereSQL == "where") {
            whereSQL = "where t.deleted='0'";
        } else {
            whereSQL = whereSQL + " and t.deleted='0'";
        }

        let datalist = await ctx.model.query("SELECT * FROM sys_menu t " + whereSQL + " order by t.order_num asc",
            { replacements: whereParams, raw: true, type: app.Sequelize.QueryTypes.SELECT });
        return datalist;
    }
}

module.exports = SysMenuService;

